<template>
  <el-dialog title="添加记账" :model-value="visible" width="520px" :fullscreen="mobile" @close="handleCancel">
    <el-form :model="addBillingForm" :rules="addBillingRules" ref="addBillingFormRef" label-width="120px">
      <el-form-item prop="type" label-width="0">
        <div style="display: flex;justify-content: center;width: 100%;">
          <el-radio-group v-model="addBillingForm.type">
            <el-radio label="1">收入</el-radio>
            <el-radio label="2">支出</el-radio>
          </el-radio-group>
        </div>
      </el-form-item>
      <el-form-item label="费用名称" prop="name">
        <el-input v-model="addBillingForm.name" placeholder="请输入费用名称"></el-input>
      </el-form-item>
      <el-form-item label="账单金额" prop="money">
        <el-input v-model="addBillingForm.money" placeholder="请输入账单金额"></el-input>
      </el-form-item>
      <el-form-item label="日期" prop="payDate">
        <el-date-picker
          v-model="addBillingForm.payDate"
          type="date"
          placeholder="请选择记账日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleOk">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup name="AddBillingDl">
import useAppStore from '@/store/modules/app'
import { parseTime } from '@/utils/ruoyi'

const { proxy } = getCurrentInstance()

const emit = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean
  },
  type: {
    type: String
  },
  form: {
    type: Object,
    default: () => {}
  }
})

const mobile = computed(() => useAppStore().device === 'mobile')
const data = reactive({
  addBillingForm: {
    type: '1',
    name: undefined,
    money: undefined,
    payDate: parseTime(new Date(), '{y}-{m}-{d}'),
  },
  addBillingRules: {
    name: [{ required: true, message: "请输入费用名称", trigger: "blur" }],
    money: [
      { required: true, message: "请输入账单金额", trigger: "blur" },
      { pattern: /^(0|([1-9][0-9]*))?(.\d{1,2})?$/, message: "请输入正确的账单金额", trigger: ["blur", "change"] }
    ],
    payDate: [{ required: true, message: "请选择记账日期", trigger: "blur" }]
  },
})

const { addBillingForm, addBillingRules } = toRefs(data)

watch(() => props.visible, (value) => {
  if (value) {
    proxy.resetForm('addBillingFormRef')
    if (props.type === 'edit') {
      addBillingForm.value = { ...props.form }
    }
  }
})

function handleCancel() {
  emit('cancel')
}
function handleOk() {
  proxy.$refs['addBillingFormRef'].validate(valid => {
    if (valid) {
      emit('ok', addBillingForm.value)
    }
  })
}
</script>
